﻿/* Copyright (C) 2012 by John Cronin
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace davserv
{
    partial class HttpServer
    {
        Response PROPFIND(Request r, uri uri, BackendManager bm, BackendManager.BackendManagerEntry b)
        {
            /* Return properties of an object */

            // The XML body provides a list of properties which are requested - interpret it here
            List<Backend.PropertyName> requested_properties = new List<Backend.PropertyName>();

            bool allprop = false;
            if (r.XmlBody == null)
                allprop = true;
            else if (r.XmlBody.Name != "propfind")
            {
                System.Diagnostics.Debug.WriteLine("PROPFIND method without propfind in xml document");
                allprop = true;
            }
            else
            {
                XmlNode n = r.XmlBody.FirstChild;
                if (n == null)
                {
                    System.Diagnostics.Debug.WriteLine("propfind element without children");
                    allprop = true;
                }
                else
                {
                    if (n.Name == "allprop")
                        allprop = true;
                    else if (n.Name == "prop")
                    {
                        foreach (XmlNode child in n.ChildNodes)
                            requested_properties.Add(new Backend.PropertyName { Name = child.Name, Namespace = child.NamespaceURI });
                    }
                    else
                        requested_properties.Add(new Backend.PropertyName { Name = n.Name, Namespace = n.NamespaceURI });
                }
            }
            if (allprop)
            {
                requested_properties.Add(new Backend.PropertyName { Name = "creationdate", Namespace = "DAV:" });
                requested_properties.Add(new Backend.PropertyName { Name = "displayname", Namespace = "DAV:" });
                requested_properties.Add(new Backend.PropertyName { Name = "getcontentlanguage", Namespace = "DAV:" });
                requested_properties.Add(new Backend.PropertyName { Name = "getcontentlength", Namespace = "DAV:" });
                requested_properties.Add(new Backend.PropertyName { Name = "getcontenttype", Namespace = "DAV:" });
                requested_properties.Add(new Backend.PropertyName { Name = "getetag", Namespace = "DAV:" });
                requested_properties.Add(new Backend.PropertyName { Name = "getlastmodified", Namespace = "DAV:" });
                requested_properties.Add(new Backend.PropertyName { Name = "lockdiscovery", Namespace = "DAV:" });
                requested_properties.Add(new Backend.PropertyName { Name = "resourcetype", Namespace = "DAV:" });
                requested_properties.Add(new Backend.PropertyName { Name = "supportedlock", Namespace = "DAV:" });
            }

            // Now generate a list of all file system objects requested
            List<uri> objects = new List<davserv.uri>();

            objects.Add(uri);
            if (b.Backend.IsCollection(b.Relative_uri) && (r.Headers["Depth"] == "1"))
            {
                Backend.UriListResponse ulr = b.Backend.GetChildren(b.Relative_uri);
                if (ulr.Status == "200")
                {
                    foreach (uri u in ulr.Value)
                    {
                        Acl cur_acl = Acl.GetAcl(u);
                        if (cur_acl.Read)
                            objects.Add(b.Backend.MountPoint.Append(u));
                    }
                }
            }

            // Generate a response
            StringBuilder sb = new StringBuilder();
            sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
            sb.Append("<D:multistatus xmlns:D=\"DAV:\">\n");

            foreach (uri o in objects)
            {
                sb.Append("<D:response>\n");
                sb.Append("<D:href>");
                sb.Append(o.ToString());
                sb.Append("</D:href>\n");

                // get the properties of the object
                Dictionary<string, List<string>> prop_values = new Dictionary<string, List<string>>();
                foreach (Backend.PropertyName prop_name in requested_properties)
                {
                    PropertyValue val = new PropertyValue { Name = prop_name };
                    Backend.StringResponse sr = b.Backend.GetProperty(o.TrimStart(b.Backend.MountPoint), prop_name);
                    val.Response = sr.Value;
                    val.Status = sr.Status;

                    if (!prop_values.ContainsKey(val.Status))
                        prop_values[val.Status] = new List<string>();

                    prop_values[val.Status].Add(val.Response);
                }

                foreach (KeyValuePair<string, List<string>> prop_value in prop_values)
                {
                    if (prop_value.Key == "404")
                        continue;

                    sb.Append("<D:propstat>\n");

                    sb.Append("<D:prop>\n");
                    foreach (string response in prop_value.Value)
                        sb.Append(response + "\n");
                    sb.Append("</D:prop>\n");

                    sb.Append("<D:status>HTTP/1.1 ");
                    sb.Append(prop_value.Key);
                    sb.Append(" ");
                    sb.Append(error_html[prop_value.Key].Reason);
                    sb.Append("</D:status>\n");

                    sb.Append("</D:propstat>\n");
                }

                sb.Append("</D:response>\n");
            }

            sb.Append("</D:multistatus>\n");

            string resp = sb.ToString();
            Response ret = Response.MakeSuccessResponse(resp);
            ret.Headers.Add("Content-Type", "text/xml; charset=\"utf-8\"");

            ret.StatusCode = "207";
            ret.ReasonPhrase = error_html["207"].Reason;
            return ret;
        }
    }
}
